package com.tang.sys.controller;

import com.tang.annotation.SystemLog;
import com.tang.enums.AppHttpCodeEnum;
import com.tang.exception.SystemException;
import com.tang.sys.ResponseResult;
import com.tang.sys.entity.User;
import com.tang.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author shankaka
 * @since 2023-04-14
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService iUserService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    //个人信息
    @GetMapping("/userInfo")
    public ResponseResult userInfo(){

        return iUserService.userInfo();
    }
    //保存修改信息
    @PutMapping("/userInfo")
    @SystemLog(businessName="更新用户信息")
    public ResponseResult updateUserInfo(@RequestBody User user){

        return iUserService.updateUserInfo(user);
    }
    //签到经验
    @PutMapping("/userExp")
    public ResponseResult addUserExp(@RequestBody User userexp){

        return iUserService.addUserExp(userexp);
    }
    //兑换
    @PutMapping("/uservipExchange")
    public ResponseResult uservipExchange(@RequestBody User userExchange){

        return iUserService.uservipExchange(userExchange);
    }



    //注册用户
    @PostMapping("/register")
    public ResponseResult register(@RequestBody User user){
        String code = user.getCode();
        // 获取 Redis 中存储的验证码
        String captcha = redisTemplate.opsForValue().get("loginCode:Code");
        // 校验验证码是否正确
        if (!StringUtils.hasText(code) || !code.equalsIgnoreCase(captcha)){
            // 验证码错误，抛出异常
            throw new SystemException(AppHttpCodeEnum.CAPTCHA_ERROR);
        }


        return iUserService.register(user);
    }
    //找回密码
    @PostMapping("/handpassword")
    public ResponseResult handpassword(@RequestBody User user){
        String code = user.getCode();
        // 获取 Redis 中存储的验证码
        String captcha = redisTemplate.opsForValue().get("loginCode:Code");
        // 校验验证码是否正确
        if (!StringUtils.hasText(code) || !code.equalsIgnoreCase(captcha)){
            // 验证码错误，抛出异常
            throw new SystemException(AppHttpCodeEnum.CAPTCHA_ERROR);
        }
        return iUserService.handpassword(user);
    }
}
